import { useState } from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'

function Users({ users, dispatch }) {
  const [newUserName, setNewUserName] = useState('')

  function createUserHandler() {
    dispatch({
      type: 'create_user',
      payload: {
        user: {
          name: newUserName,
        },
      },
    })
  }

  function deleteUserHandler(id) {
    dispatch({
      type: 'delete_user',
      payload: {
        id,
      },
    })
  }

  return (
    <div className="users page">
      <h1>User Page</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            ID: {user.id}
            <br />
            姓名：{user.name}
            <button onClick={() => deleteUserHandler(user.id)}>删除用户</button>
            <Link to={'/users/' + user.id}>个人页面</Link>
          </li>
        ))}
      </ul>
      <input
        type="text"
        value={newUserName}
        onChange={e => setNewUserName(e.target.value)}
      />
      <button onClick={createUserHandler}>创建用户</button>
    </div>
  )
}

// export default connect(model => {
//   return {
//     users: model.users,
//   }
// })(Users)

export default connect(({ users }) => ({ users }))(Users)
